/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package csvconvertor;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * @author sajin
 */
public class CSVWriter {
    public CSVWriter(String fileName) throws FileNotFoundException {
        csvFile = new FileOutputStream(fileName);
        
    }

    protected void finalise() throws Throwable {
        csvFile.close();
    }

    public void writeHeaderFields(String header[]) throws IOException {
        boolean firstField = true; 
        for (String field: header) {
            
            if ( field.contains(",")) {
               // The field contains atleast one comma.
               field = "\"" + field + "\"";

               if ( ! firstField )
                csvFile.write(",".getBytes());      // Add a comma after
                                                    // The field is written.
               if ( firstField )
                   firstField = false;
               csvFile.write(field.getBytes());
            }
            else {
                if ( !firstField )
                    csvFile.write(",".getBytes()); // Add a comma after
                                                   // The field is written.
                if ( firstField )
                    firstField = false;
                csvFile.write(field.getBytes());
            }
        }        
    }

    public void writeFields(String fields[]) throws IOException {
        // Add a new line.
        csvFile.write("\n".getBytes());

        boolean firstField = true;

        for (String field : fields) {
            if ( !firstField )
                csvFile.write(",".getBytes() );
            else
                firstField = false;
            if ( field.contains(","))
                field = "\"" + field + "\"";
            csvFile.write(field.getBytes());
        }
    }

    protected FileOutputStream csvFile;
}
